#include<stdio.h>
#include<fcntl.h>
#include<string.h>
#include<stdlib.h>
#include<malloc.h>
#include "../include/meta.h"
#include "../include/vfs_errorcodes.h"
char * update_file( char* dest_path, char* src_path)
{
	char result[100];
	if(root==NULL)
	{
		strcpy(result,"updatefile_FAILURE ");
		strcat(result,ERR_VFS_UPDATEFILE_04);
		sprintf(str, "%s",result);
		return str;
		
	}	
	if(dest_path==NULL || src_path==NULL)
	{
		strcpy(result,"updatefile_FAILURE ");
		strcat(result,ERR_VFS_UPDATEFILE_00);
		sprintf(str, "%s",result);
		return str;
	}
	
	FILE *fp_src, *fp,*fp_new;
	fp= fopen(mounted_vfs,"rb+");
	fp_src = fopen(src_path, "rb+");
	fp_new=fp_src;
	if(fp_src==0)
	{
		strcpy(result,"updatefile_FAILURE ");
		strcat(result,ERR_VFS_UPDATEFILE_01);		//Changed
		//strcat(result,ERR_VFS_UPDATEFILE_01);
		sprintf(str, "%s",result);
		return str;
	}
	int sz;
	fseek(fp_new,0,SEEK_END);
	sz = ftell(fp_new);
	if(sz>1024)
	{	
		strcpy(result,"updatefile_FAILURE ");
		strcat(result,ERR_VFS_UPDATEFILE_03);
		sprintf(str, "%s",result);
		return str;
	}
	char *token1,*token2;
	char buffer[1024];
	token1 = strtok(src_path,"/");
	while(token1!=NULL)
	{
		token2=token1;
		token1=strtok(NULL,"/");
	}
	token1 = strtok(token2,".");
	token2 =strtok(NULL,".");
	//if(strcmp(token2,"txt")!=0 || strcmp(token2,"dat")!=0 )
	//{
	//	return ERR_VFS_UPDATEFILE_03;
	//}

	/*if(main_header_var->max_no_file_descriptors == main_header_var->no_used_file_descriptors)
	{
		strcpy(result,"updatefile_FAILURE ");		//commented 
		strcat(result,ERR_VFS_UPDATEFILE_04);
		sprintf(str, "%s",result);
		return str;
		
	}*/
		
	int index=bst_search(bstroot,dest_path);

	if(index==-1)
	{
		strcpy(result,"updatefile_FAILURE ");
		strcat(result,ERR_VFS_UPDATEFILE_01);	//Changed
		//strcat(result,ERR_VFS_UPDATEFILE_02);
		sprintf(str, "%s",result);
		return str;
		
	}
	
	/*node *updatenode = (node*)checkpath_returnnode(dest_path,root) ;
	if(updatenode== NULL)
	{
		strcpy(result,"updatefile_FAILURE ");
		strcat(result,ERR_VFS_UPDATEFILE_01);	//Changed
		//strcat(result,ERR_VFS_UPDATEFILE_02);
		sprintf(str, "%s",result);
		return str;
		
	}*/
	//int index = updatenode->index;
	
	int block_no = fd[index].block_number;
	int offset = main_header_var->headersize + 1024*(block_no-1);
	char buffer1[1024];
	fseek(fp,offset,SEEK_SET);
	fread(buffer,1024,1,fp_src);
	fread(buffer1,1024,1,fp);
	fseek(fp,offset,SEEK_SET);
	printf("%s",buffer1);
	int x=ftell(fp);
	if(x == offset)
	fwrite(buffer,1024,1,fp);
	fclose(fp);
	return "updatefile_SUCCESS";
}
		
		

		
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	


